import 'package:flutter/foundation.dart';
import '../models/question.dart';
import 'storage_service.dart';

class WrongQuestionProvider with ChangeNotifier {
  final StorageService _storageService = StorageService();

  List<Question> _wrongQuestions = [];
  bool _isLoading = false;
  bool _hasError = false;
  String _errorMessage = '';
  Map<String, int> _stats = {};

  // Getters
  List<Question> get wrongQuestions => _wrongQuestions;
  bool get isLoading => _isLoading;
  bool get hasError => _hasError;
  String get errorMessage => _errorMessage;
  Map<String, int> get stats => _stats;

  // 加载错题集统计
  Future<void> loadStats() async {
    _isLoading = true;
    notifyListeners();

    try {
      _stats = await _storageService.getWrongQuestionStats();
      print("错题统计加载成功: $_stats");
    } catch (e) {
      _hasError = true;
      _errorMessage = e.toString();
      print("错题统计加载失败: $e");
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 加载错题集，添加调试日志
  Future<void> loadWrongQuestions(int rank, int type) async {
    _isLoading = true;
    _hasError = false;
    notifyListeners();

    try {
      print("开始加载错题集: 车型=$rank, 科目=$type");
      _wrongQuestions = await _storageService.getWrongQuestions(rank, type);
      print("错题集加载完成，数量: ${_wrongQuestions.length}");
    } catch (e) {
      _hasError = true;
      _errorMessage = e.toString();
      print("错题集加载失败: $e");
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 添加到错题集
  Future<void> addToWrongQuestions(Question question) async {
    try {
      print("添加题目到错题集: ID=${question.id}");
      await _storageService.addWrongQuestion(question);
      await loadStats(); // 更新统计
      notifyListeners();
    } catch (e) {
      _hasError = true;
      _errorMessage = e.toString();
      print("添加错题失败: $e");
      notifyListeners();
    }
  }

  // 从错题集移除
  Future<void> removeFromWrongQuestions(int questionId) async {
    try {
      await _storageService.removeWrongQuestion(questionId);
      _wrongQuestions.removeWhere((q) => q.id == questionId);
      await loadStats(); // 更新统计
      notifyListeners();
    } catch (e) {
      _hasError = true;
      _errorMessage = e.toString();
      notifyListeners();
    }
  }

  // 检查是否为错题
  Future<bool> isWrongQuestion(int questionId) async {
    return await _storageService.isWrongQuestion(questionId);
  }
}
